var api = require('../../utils/api.js')
var $ = require('../../utils/util.js')
var mainWirteUtil=require('../../utils/mainWirteUtil.js')
var regeneratorRuntime = require('../../utils/runtime.js')
var app = getApp()
var Store = app.Store

Page({

  /**
   * 页面的初始数据
   */
  data: {
    style:'',//canvas样式
    scale: 0.5,  //缩放倍数
    clickXY:[],//按键坐标点
    scrollLeft: 0,//画布先做拖动距离
    isShowYK:false,//遥控弹窗
    isConfirm1:false,//遥控人员认证窗口
    isConfirm2:false,//监控人员认证窗口
    isPass1:false,//遥控人员认证是否通过
    isPass2:false,//监控人员是否通过
    YkUsers:[],//遥控人员列表
    YKInfo:{},
    key:null,//订阅消息的路由
    path:"",//之接线图路径

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    app._clearFromCache();//清楚store缓存
    var zf_list = await app._selected() // 获取站房
    this.setData({ 
      title: zf_list.data[0].list[0].dept_name,//站房名称
      stationId: zf_list.data[0].list[0].station, // 站房id
    }) 
    wx.setNavigationBarTitle({
      title:zf_list.data[0].list[0].dept_name,//设置标题
    })

    var system=wx.getSystemInfoSync();
    var context = wx.createCanvasContext('myCanvas', this) //1.创建carvas实例对象，方便后续使用。
      this.setData({
        statusHeight:system.statusBarHeight+45,
        context:context
      })
    this.getYkUsers();//获取遥控人员列表 
    this.getMainWrite();//画图

  },
/**
 * 生命周期函数--监听页面显示
 */
onShow: function () {
  var form = Store.getState().formInfor.form
    if (!form.selected) {
      if(!$.isNull(this.data.setInterval_id)){
        console.log("ws手动断开重连机制")
        this.stomp(this.data.stationId);
      }
      return
    }
    var key = form.key
    switch (key) { 
      case 'selected': // 企业和站房列表接口 
        this.setData({
          title:form.selected.dept_name,
          stationId: form.selected.station, // 站房id
        })
        wx.setNavigationBarTitle({
          title: form.selected.dept_name,
        })
        this.getMainWrite();//画图
        break
    }
    app._clearFromCache();
},
onUnload(){
  console.log("页面卸载,关闭ws连接")
  try {
    //关闭连接
    wx.closeSocket();
    console.log(this.data.setInterval_id);
    clearInterval(this.data.setInterval_id);
  } catch (error) {
    
  }
},
getMainWrite(){
  var params={"station":this.data.stationId,"path":this.data.path};
  wx.showLoading({
    title: '加载中...',
    mask:true
  })
  api.$post(api.mainWrite.mainWrite,params).then(res=>{
    wx.hideLoading();
    //数据源
    var data=res.data;
    if(!$.isNull(data.msg)){
      $.toast(data.msg);
      return;
    }
    //画布大小与颜色设置
    var backgroundColor = this.colorRGBtoHex(mainWirteUtil.jsRgb(data.drawHead.drawBkColor));
    this.setData({
      width:data.drawHead.screenWidth,
      height:data.drawHead.screenHeight,
      style: 'width:'+data.drawHead.screenWidth+'px;'+'height:'+data.drawHead.screenHeight+'px;'+'background-color:'+backgroundColor+';',
      drawList : data.list,
    })
    //cnavas 画图数据
    this.drawImage(this.data.context,this.data.drawList);
    this.stomp(this.data.stationId);
  })
},
drawImage(context,drawList){//画布绘图函数
    var clickXY = [];
    this.setData({
      clickXY:clickXY
    })
    context.clearRect(0, 0, this.data.width,this.data.height);
    context.scale(this.data.scale, this.data.scale);
    for (let i = 0; i < drawList.length; i++) {
      mainWirteUtil.draw(null, context, drawList[i],clickXY);
    }
    var that=this;
    context.draw(false,function(){
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: that.data.width,
        height: that.data.height,
        canvasId: 'radarCanvas',
        success: function(res) {
          that.setData({ img: res.tempFilePath});
        }
      });
    });
},
colorRGBtoHex(color) {//颜色格式转换函数
    var rgb = color.split(',');
    var r = parseInt(rgb[0].split('(')[1]);
    var g = parseInt(rgb[1]);
    var b = parseInt(rgb[2].split(')')[0]);
    var hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
    return hex;
},
plus(){//画布放大
  this.setData({
    scale:this.data.scale*1.1
  })
  this.drawImage(this.data.context,this.data.drawList)
},
minus(){//画布缩小
  this.setData({
    scale:this.data.scale*0.9
  })
  this.drawImage(this.data.context,this.data.drawList)
},
onclick(e){//画布点击事件
  const zoom=this.data.scale;
  const x = e.detail.x +this.data.scrollLeft ;
  const y = e.detail.y  ;
console.log(this.data.clickXY)
  for(let i of this.data.clickXY) {
    if(x > zoom * i.x -10 && x < zoom * (i.x + i.w)+10 && y > zoom * i.y-10 && y < zoom * (i.y + i.h)+10) {
      if (i.c === 210) {
        console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
          console.log("点击了的遥控按钮===============210");
          console.log("遥信测点号",i.d)
          console.log(i);
          var params={
            YXDH:i.d,
            YXCH:this.data.stationId
          }
          api.$post(api.yk.info, params).then((res) => {
            if(res.data.CDH)
              this.setData({
                YKInfo:res.data,
                isShowYK:true
              })
            else
             $.toast("此节点不支持遥控功能")
          })
      } else {
        console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
        console.log("点击了高低压系统切换按钮xxxxxxxxxxxxxxxx");
        console.log("文件名称",i.f)
        this.setData({path:i.f?i.f:''})
        this.getMainWrite();
      }
    }
  }
},
binddragging(e){//画布左右拖动
  this.setData({
    scrollLeft:e.detail.scrollLeft
  })
},
onClose(){//弹窗关闭
  setTimeout(() => {
    this.setData({
      isShowYK:false
    })
  }, 200);
},
opendeal(e){//分闸操作
  var item=$.detail(e);
  var YKNO=item.item.YKNO;
  if(YKNO==0 || YKNO==null || YKNO==''){
    $.toast('未配置遥控号,暂不支持遥控功能');
    return;
  }

        if(!this.data.isPass1){
          this.setData({
            isConfirm1:true
         })
         return
        }else if(!this.data.isPass2){
          this.setData({
            isConfirm2:true
         })
         return
        }

            //遥控
              var params={
                YKNO:YKNO,//遥控号
                YXCH:item.item.YXCH,//遥信厂号
                v1:false,//分闸
                company:item.item.company,// 企业名称
                factory:item.item.YXCM, //厂站名称
                line_name :item.item.YXXLM,//线路名称
                point :item.item.YXDM,//测点名称
                opera :this.data.opera_name,//操作人
                monitor :this.data.monitor_name,//监控人
                redis_key:item.item.CODE,//redis 主键
              };
              api.$post(api.yk.YKOperation,params).then((res)=>{
                    if(res.code==0){
                      $.toast('分闸命令已发送');
                      var count=0;
                      // var i=setInterval(()=>{
                      //   count++;
                      //   api.$post(api.yk.getYKStatus,params1).then((res)=>{
                      //     if(res.data.VALUE==0){
                      //       // $.toast('分闸成功,正在为你刷新列表');
                      //       // this.getYxList();//获取遥信列表
                      //       // console.log('update')
                      //       clearInterval(i)
                      //     }
                      //     if(count>10){
                      //       // $.toast('分闸失败,请查看设备是否在线');
                      //       clearInterval(i)
                      //     }
                      //   })
                      // },2000)

                    }else{
                      // $.toast('未知错误');
                    }
              })

},
closedeal(e){//合闸操作
  var item=$.detail(e);
  var YKNO=item.item.YKNO;
  if(YKNO==0 || YKNO==null || YKNO==''){
    $.toast('未配置遥控号,暂不支持遥控功能');
    return;
  }

        if(!this.data.isPass1){
          this.setData({
            isConfirm1:true
         })
         return
        }else if(!this.data.isPass2){
          this.setData({
            isConfirm2:true
         })
         return
        }

              //遥控
              var params={
                YKNO:YKNO,//遥控号
                YXCH:item.item.YXCH,//遥信厂号
                v1:true,//合闸
                company:item.item.company,// 企业名称
                factory:item.item.YXCM, //厂站名称
                line_name :item.item.YXXLM,//线路名称
                point :item.item.YXDM,//测点名称
                opera :this.data.opera_name,//操作人
                monitor :this.data.monitor_name,//监控人
                redis_key:item.item.CODE,//redis 主键
              };
              api.$post(api.yk.YKOperation,params).then((res)=>{
                if(res.code==0){
                  $.toast('合闸命令已发送');
                  var count=0;
                  // var i=setInterval(()=>{
                  //   count++;
                  //   api.$post(api.yk.getYKStatus,params1).then((res)=>{
                  //     if(res.data.VALUE==1){
                  //       // $.toast('合闸成功,正在为你刷新列表');
                  //       // this.getYxList();//获取遥信列表
                  //       // console.log('update')
                  //       clearInterval(i)
                  //     }
                  //     if(count>10){
                  //       // $.toast('合闸失败,请查看设备是否在线');
                  //       clearInterval(i)
                  //     }
                  //   })
                  // },2000)
                }else{
                  // $.toast('未知错误');
                }
              })
      
  
},
change1(e){//遥控人员下拉列表 change
  var item=e.detail;
  this.setData({
    opera_id:item.id,
    opera_name:item.name 
  })
},
change2(e){//监控人员下拉列表 change
  var item=e.detail;
  this.setData({
    monitor_id:item.id,
    monitor_name:item.name
  })
},
confirmHandle(){//遥控人员认证
    if($.isNull(this.data.opera_id)){
      $.toast('请选择遥控人员');
    }else if($.isNull(this.data.opera_password)){
      $.toast('请先输入密码');
    }else{
      var params={
        id:this.data.isPass1?this.data.monitor_id:this.data.opera_id,
        password:this.data.isPass1?this.data.monitor_password:this.data.opera_password,
        user_name:this.data.isPass1?this.data.monitor_name:this.data.opera_name,
      }
      // console.log('params',params);
      var that=this;
      api.$post(api.yk.checkUser,params).then((res)=>{
        if(res.code==0){
          if(this.data.isPass1){
            if(that.data.opera_id==that.data.monitor_id){
              $.toast('遥控人员和监控人员不能相同')
              return
            }
            $.toast('认证已完成,可以开始进行分合闸动作')
            this.setData({
              isPass2:true,
            })
          }else{
            $.toast('正在开启监控人员认证')
            setTimeout(() => {
              that.setData({
                isPass1:true,
                isConfirm2:true
              })
            }, 1300);
          }
        }
      })
    }
},
getYkUsers(){//遥控人员列表获取
  var params={};
  api.$post(api.yk.YkUsers,params).then((res)=>{
    this.setData({
      YkUsers:res.data
    });
  });
},
getYKInfo(){//遥控列表获取

},
input_handle(e) { //##input 输入##
  this.setData({
    [e.currentTarget.dataset.key]: e.detail.value
  })
},
selectStation(){ //选择场站
      this.setData({
        eqIndex: 1, // ---该需求了---
        isShowPop: false
      })
      Store.dispatch({
        type: 'SET_FROM',
        form: {
          key: 'selected', // 后台要的更改字段 
          type: 3, // 表单类型 1： radio  2：select 3:特殊的radio
          config: {

          },
        },
      })
      $.linkurl(`/pages/main/chooseForm/chooseForm`)
     
},
stomp(stationId){
  if(!$.isNull(this.data.key)||wx.getStorageSync('wsOpenType')==1){//切换连接前关闭链接
    try{
      if(wx.getStorageSync('wsOpenType')==1) wx.setStorageSync('wsOpenType', 2)
      wx.closeSocket();
      clearInterval(this.data.setInterval_id);
    }catch(e){
    }
  }
  var that=this;
  var context=this.data.context;
  var drawList=that.data.drawList;
  const yxs = [205, 207, 210, 211, 212, 214, 215, 216, 233];
  
  
  function fixZeroStart(str, n) {
    return (Array(n).join(0) + str).slice(-n);
  }
  
  const keyStation = fixZeroStart(parseInt(stationId / 65535).toString(), 4) + fixZeroStart((stationId % 65535).toString(16), 4);
  
  var socketOpen = false
  var socketMsgQueue = new Array()
  function sendSocketMessage(msg) {
      // console.log('send msg:')
      // console.log(msg);
      if (socketOpen) {
          wx.sendSocketMessage({
              data: msg
          })
      } else {
          socketMsgQueue.push(msg)
      }
  }

  /////////////////////////////////////////////////////
  var ws = {
      send: sendSocketMessage,
      onopen: null,
      onmessage: null
  }
  wx.connectSocket({
      url:api.url.replace("https://","wss://")+"/wss"
  })
  wx.onSocketOpen(function (res) {
      console.log('WebSocket连接已打开！')

      socketOpen = true
      for (var i = 0; i < socketMsgQueue.length; i++) {
          sendSocketMessage(socketMsgQueue[i])
      }
      socketMsgQueue = []

      ws.onopen && ws.onopen()
  })

  wx.onSocketMessage(function (res) {
      // console.log('收到onmessage事件:', res)
      ws.onmessage && ws.onmessage(res)
  })




  var Stomp = require('../../utils/stomp.js').Stomp;
  Stomp.setInterval = function () { }
  Stomp.clearInterval = function () { }
  var client = Stomp.over(ws);


  var destination1 = '/exchange/ruidcn/ruidcn.dist.' + keyStation + '.ai';
  var destination2 = '/exchange/ruidcn/ruidcn.dist.' + keyStation + '.di';


  // client.connect('alarm', 'alarm', function (sessionId) {
    client.connect('admin', 'RDRJ321rdrj123RUId', function (sessionId) {
      


      console.log('sessionId', sessionId)

      client.subscribe(destination1, function (body, headers) {
        // console.log('From MQ 1:', body);
        var dist=[];
        try {
           dist = JSON.parse( body.body );
          //  console.log(dist)
          } catch(e) {
            // console.log('客户端发送心跳包MQ1:', body);
              return ;
          }
          for (let i = 0; i< dist.length; i++) {
            for (let j = 0; j < drawList.length; j++) {
              if (drawList[j].mpyclass === 106) {
                // console.log(111111111)
                if (drawList[j].xuHao === dist[i].tag){
                  drawList[j].checkM1 = dist[i].val.toFixed(2);
                  mainWirteUtil.draw(null, context, drawList[j]);
                } else if (drawList[j].yk1 === dist[i].tag) {
                  drawList[j].checkM2 = dist[i].val.toFixed(2);
                  mainWirteUtil.draw(null, context, drawList[j]);
                } else if (drawList[j].yk2 === dist[i].tag) {
                  drawList[j].checkC1 = dist[i].val.toFixed(2);
                  mainWirteUtil.draw(null, context, drawList[j]);
                }
              } else if (drawList[j].mpyclass === 238 && drawList[j].xuHao === dist[i].tag) {
                // console.log(22222222222)
                drawList[j].data = dist[i].val.toFixed(2);
                mainWirteUtil.draw(null, context, drawList[j]);
              }
            }
          }
          context.draw(true);
          that.setData({
            drawList:drawList
          })
      }, {
				id: keyStation + ".ai"
			});

      client.subscribe(destination2, function (body, headers) {
        // console.log('From MQ 2:', body);
        var dist=[];
        try {
           dist = JSON.parse( body.body );
          } catch(e) {
            // console.log('客户端发送心跳包MQ2:', body);
              return ;
          }
				for (let i = 0; i< dist.length; i++) {
					for (let j = 0; j < drawList.length; j++) {
						if (yxs.indexOf(drawList[j].mpyclass) !== -1 && drawList[j].xuHao == dist[i].tag) {
              // console.log(33333)
							drawList[j].yx = dist[i].val;
              mainWirteUtil.draw(null, context, drawList[j]);
						}
					}
				}
        context.draw(true);
        that.setData({
          drawList:drawList
        })
      }, {
        id: keyStation + ".di"
      });

      var setInterval_id=setInterval(function(){//心跳包机制,防止断开连接
        client.send(destination1, { priority: 9 }, 'hello !');
        client.send(destination2, { priority: 9 }, 'hello !');
      },15000)
      that.setData({
        setInterval_id:setInterval_id
      })


      // if (that.data.key) {
			// 	client.unsubscribe(key + ".ai");
			// 	client.unsubscribe(key + ".di");
			// }
			that.setData({
        key:keyStation
      })
  })
},



})